package com.nl.controller.common.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

/**
 * 基于 httpclient  http工具类
 * @author sj
 *
 */
public class HttpClientUtil {

    public static final String CHARSET = "UTF-8";
    private static Map<String, String> headers = new HashMap<String, String>();  

    public static String httpPost(String url, Map<String, String> param) throws Exception{  
        //System.out.println("httpPost URL [" + url + "] start ")
        DefaultHttpClient httpclient = null;  
        HttpPost httpPost = null;  
        HttpResponse response = null;  
        HttpEntity entity = null;  
        String result = "";  
        StringBuffer suf = new StringBuffer();  
        try {  
            httpclient = new DefaultHttpClient();  
            // 设置cookie的兼容性---考虑是否需要  
            httpPost = new HttpPost(url);
            // 设置各种头信息  
            for (Entry<String, String> entry : headers.entrySet()) {  
                httpPost.setHeader(entry.getKey(), entry.getValue());  
            }  
            List<NameValuePair> params = new ArrayList<NameValuePair>();  
            // 传入各种参数  
            if (null != param) {  
                for (Entry<String, String> set : param.entrySet()) {  
                    String key = set.getKey();  
                    String value = set.getValue() == null ? "" : set.getValue().toString();  
                    params.add(new BasicNameValuePair(key, value));  
                    suf.append(" [" + key + "-" + value + "] ");  
                }  
            }  
            StringEntity se = new UrlEncodedFormEntity(params);
    		se.setContentEncoding("UTF-8");
    		se.setContentType("application/json");// 发送json需要设置contentType
            httpPost.setEntity(se);  
            //System.out.println("params " + params)
            // 设置连接超时时间  
            HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),20000);  
            // 设置读数据超时时间  
            HttpConnectionParams.setSoTimeout(httpPost.getParams(),20000);  
            response = httpclient.execute(httpPost);  
            int statusCode = response.getStatusLine().getStatusCode();  
            System.out.println("====statusCode:  [" + statusCode + "]=======");  
            if (statusCode != HttpStatus.SC_OK) {  
          	  //System.out.println("HttpStatus ERROR" + "Method failed: "+ response.getStatusLine())
              return "";  
             } else {  
                entity = response.getEntity();  
                if (null != entity) {  
                    byte[] bytes = EntityUtils.toByteArray(entity);  
                    result = new String(bytes, "UTF-8");  
                } else {  
                	//System.out.println("httpPost URL [" + url+ "],httpEntity is null.")
                }  
                return result;  
           }  
            
        } catch (Exception e) {  
        	//System.out.println("httpPost URL [" + url + "] error, ")
        	throw e;
        } finally {  
            if (null != httpclient) {  
                httpclient.getConnectionManager().shutdown();
            }  
            
            System.out.println("RESULT:  [" + result + "]");  
        }  
    }
    
    public static String postMethod(String url, Map<String, String> map)
			throws Exception {
		HttpClient client = new HttpClient(new HttpClientParams(),
				new SimpleHttpConnectionManager(true));
		PostMethod postMethod = new PostMethod(url);
		postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
		List<org.apache.commons.httpclient.NameValuePair> nameValuePairs = new ArrayList<org.apache.commons.httpclient.NameValuePair>();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			nameValuePairs.add(new org.apache.commons.httpclient.NameValuePair(entry.getKey(), entry.getValue()));
		}
		String response="";
		try {
			org.apache.commons.httpclient.NameValuePair[] requestBody = new org.apache.commons.httpclient.NameValuePair[nameValuePairs.size()];
			nameValuePairs.toArray(requestBody);
			postMethod.setRequestBody(requestBody);
			client.executeMethod(postMethod);
			System.out.println(postMethod.getStatusLine());
			response = postMethod.getResponseBodyAsString();
			System.out.println(response);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			postMethod.releaseConnection();
		}
		return response;
	}
    
	/**
	 * 
	 * desc:
	 * @author sj
	 * @date 2016-5-16 上午10:32:36
	 * @param parameterMap
	 * @return
	 * @throws Exception
	 */
	public static String sendHttpRequest(String url, Map<String,String> parameterMap) throws Exception{
		StringBuffer parameterBuffer = new StringBuffer();
        if (parameterMap != null) {
            Iterator iterator = parameterMap.keySet().iterator();
            String key = null;
            String value = null;
            while (iterator.hasNext()) {
                key = (String)iterator.next();
                if (parameterMap.get(key) != null) {
                    value = (String)parameterMap.get(key);
                } else {
                    value = "";
                }
                
                parameterBuffer.append(key).append("=").append(value);
                if (iterator.hasNext()) {
                    parameterBuffer.append("&");
                }
            }
        }
        System.out.println("POST parameter : " + parameterBuffer.toString().trim().replaceAll("\\+", "%2B").replaceAll("\\n", ""));
        URL localURL = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection)localURL.openConnection();
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));
        httpURLConnection.setRequestMethod("POST"); //设定请求的方法为"POST"，默认是GET
        httpURLConnection.setConnectTimeout(20000); //连接主机的超时时间（单位：毫秒）
        httpURLConnection.setReadTimeout(20000); //从主机读取数据的超时时间（单位：毫秒）
        OutputStream outputStream = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
		try {
			outputStream = httpURLConnection.getOutputStream();
			outputStream.write(parameterBuffer.toString().trim().replaceAll("\\+", "%2B").replaceAll("\\n", "").getBytes("utf-8"));
            httpURLConnection.connect();
            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);
            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
            
		} catch (Exception e) {
			throw e;
		}finally {
            if (outputStream != null) {
                outputStream.close();
            }
            if (reader != null) {
                reader.close();
            }
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
		return resultBuffer.toString();
	}
	
	public static String httpPostForZx(String url, Map<String, String> param) throws Exception{  
        //System.out.println("httpPost URL [" + url + "] start ") 
        DefaultHttpClient httpclient = null;  
        HttpPost httpPost = null;  
        HttpResponse response = null;  
        HttpEntity entity = null;  
        String result = "";  
        StringBuffer suf = new StringBuffer();  
        try {  
            httpclient = new DefaultHttpClient();  
            // 设置cookie的兼容性---考虑是否需要  
            httpPost = new HttpPost(url);
            // 设置各种头信息  
            for (Entry<String, String> entry : headers.entrySet()) {  
                httpPost.setHeader(entry.getKey(), entry.getValue());  
            }  
            List<NameValuePair> params = new ArrayList<NameValuePair>();  
            // 传入各种参数  
            if (null != param) {  
                for (Entry<String, String> set : param.entrySet()) {  
                    String key = set.getKey();  
                    String value = set.getValue() == null ? "" : set.getValue().toString();  
                    params.add(new BasicNameValuePair(key, value));  
                    suf.append(" [" + key + "-" + value + "] ");  
                }  
            }  
            StringEntity se = new UrlEncodedFormEntity(params);
    		se.setContentEncoding("UTF-8");
    		se.setContentType("application/x-www-form-urlencoded");// 发送json需要设置contentType
            httpPost.setEntity(se);  
            // 设置连接超时时间  
            HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),20000);  
            // 设置读数据超时时间  
            HttpConnectionParams.setSoTimeout(httpPost.getParams(),20000);  
            response = httpclient.execute(httpPost);  
            int statusCode = response.getStatusLine().getStatusCode();  
            System.out.println("====statusCode:  [" + statusCode + "]=======");  
            if (statusCode != HttpStatus.SC_OK) {  
              return "";  
             } else {  
                entity = response.getEntity();  
                if (null != entity) {  
                    byte[] bytes = EntityUtils.toByteArray(entity);  
                    result = new String(bytes, "UTF-8");  
                } 
                return result;  
           }  
            
        } catch (Exception e) {  
        	throw e;
        } finally {  
            if (null != httpclient) {  
                httpclient.getConnectionManager().shutdown();
            }  
            
            System.out.println("RESULT:  [" + result + "]");  
        }  
    }
	
	public static Map<String,String> httpPostWithXml(String url, String reqxml
            ,String charset,Map<String, String> headers){  
        Map<String,String>retMap = new HashMap<String,String>();
        DefaultHttpClient httpclient = null;  
        HttpPost httpPost = null;  
        HttpResponse response = null;  
        HttpEntity entity = null;  
        String retMsg = "";
        String retCode="-1";
        try {  
            httpclient = new DefaultHttpClient();  
            // 设置cookie的兼容性---考虑是否需要  
//          httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,  
//                  CookiePolicy.BROWSER_COMPATIBILITY) 
            httpPost = new HttpPost(url); 
            httpPost.setHeader("Content-Type", "text/xml;charset="+charset);
            // 设置各种头信息
            if(headers!=null){
                for (Entry<String, String> entry : headers.entrySet()) {  
                    httpPost.setHeader(entry.getKey(), entry.getValue());  
                }  
            }
            StringEntity entityParam = new StringEntity(reqxml,charset);//解决中文乱码问题    
            httpPost.setEntity(entityParam);
            // 设置连接超时时间  
            HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),30000);  
            // 设置读数据超时时间  
            HttpConnectionParams.setSoTimeout(httpclient.getParams(),30000);  
            response = httpclient.execute(httpPost);  
          int statusCode = response.getStatusLine().getStatusCode();  
          if (statusCode != HttpStatus.SC_OK) {  
              retMsg= "HttpStatus ERROR" + " Method failed: "+ response.getStatusLine(); 
              retCode="-2";
          } else {  
            entity = response.getEntity();  
            if (null != entity) { 
                byte[] bytes = EntityUtils.toByteArray(entity); 
                retCode="0";
                retMsg = new String(bytes, charset);  
            } else {  
                retCode="-3";
                retMsg="httpPost URL [" + url+ "],httpEntity is null";
            }  
          }  
        } catch (Exception e) {  
            retCode="-99";
            retMsg="httpPost URL [" + url + "] error: "+e.getMessage();
        } finally {  
            if (null != httpclient) {  
                httpclient.getConnectionManager().shutdown();
            }  
        } 
        retMap.put("retCode", retCode);
        retMap.put("retMsg", retMsg);
        return retMap;
    }
	
	public static Map<String,String> httpPostWithXml(String url, String reqxml
	        ,String reqcharset,String respcharset,Map<String, String> headers){  
	    Map<String,String>retMap = new HashMap<String,String>();
	    DefaultHttpClient httpclient = null;  
	    HttpPost httpPost = null;  
	    HttpResponse response = null;  
	    HttpEntity entity = null;  
	    String retMsg = "";
	    String retCode="-1";
	    try {  
	        httpclient = new DefaultHttpClient();  
	        // 设置cookie的兼容性---考虑是否需要  
//          httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,  
//                  CookiePolicy.BROWSER_COMPATIBILITY) 
	        httpPost = new HttpPost(url); 
	        httpPost.setHeader("Content-Type", "text/xml;charset="+reqcharset);
	        // 设置各种头信息
	        if(headers!=null){
	            for (Entry<String, String> entry : headers.entrySet()) {  
	                httpPost.setHeader(entry.getKey(), entry.getValue());  
	            }  
	        }
	        StringEntity entityParam = new StringEntity(reqxml,reqcharset);//解决中文乱码问题    
	        httpPost.setEntity(entityParam);
	        // 设置连接超时时间  
	        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),30000);  
	        // 设置读数据超时时间  
	        HttpConnectionParams.setSoTimeout(httpclient.getParams(),30000);  
	        response = httpclient.execute(httpPost);  
	        int statusCode = response.getStatusLine().getStatusCode();  
	        if (statusCode != HttpStatus.SC_OK) {  
	            retMsg= "HttpStatus ERROR" + " Method failed: "+ response.getStatusLine(); 
	            retCode="-2";
	        } else {  
	            entity = response.getEntity();  
	            if (null != entity) { 
	                byte[] bytes = EntityUtils.toByteArray(entity); 
	                retCode="0";
	                retMsg = new String(bytes, respcharset);  
	            } else {  
	                retCode="-3";
	                retMsg="httpPost URL [" + url+ "],httpEntity is null";
	            }  
	        }  
	    } catch (Exception e) {  
	        retCode="-99";
	        retMsg="httpPost URL [" + url + "] error: "+e.getMessage();
	    } finally {  
	        if (null != httpclient) {  
	            httpclient.getConnectionManager().shutdown();
	        }  
	    } 
	    retMap.put("retCode", retCode);
	    retMap.put("retMsg", retMsg);
	    return retMap;
	}
	
	
}